
import csv
import datetime

from balancer import Balance
from balancer import BalanceAccount

class Historian:
    """Responsible for recording, searching, and extracting history entries."""

    def __init__(self, gm):
        self.__gm = gm

    
    def add_run(self, results, desc):
        """Record the run."""
        f = open(self.__gm.get_home() + 'history.csv', 'a+')
        now = datetime.datetime.now()
        try:
            writer = csv.writer(f)

            for balance in results.get_accounts():
                writer.writerow([now,
                        balance.get_source().get_source_uuid(),
                        balance.get_moniker(), 
                        balance.get_uuid(), 
                        balance.get_name(),
                        balance.get_balance()])

        finally:
            f.close()

    
    def last_run(self):
        """Return the last registered run."""
        f = open(self.__gm.get_home() + 'history.csv', 'r')
        try:
            reader = csv.reader(f)

            accts = []
            oldTime = None

            for row in reader:
                (time, source, moniker, acctUuid, name, balance) = row
                if oldTime != time:
                    accts = []
                    oldTime = time

                source = self.__gm.get_balancer(source)
                accts.append(BalanceAccount(source, moniker=moniker, uuid=acctUuid, balance=balance, name=name))

            return Balance(accts)

        finally:
            f.close()
